//
//  WJComposeView.swift
//  WJWeiBo
//
//  Created by wangjun on 16/7/28.
//  Copyright © 2016年 wangjun. All rights reserved.
//

import UIKit
import pop
class WJComposeView: UIView {
    
    private var composeButtonInfos: [WJComposeButtonInfo] = [WJComposeButtonInfo]()
    
    var target: UIViewController?
    
    lazy var buttons: [WJComposeButton] = [WJComposeButton]()
    
    //init
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width:  SCREENW, height: SCREENH))
        setupUI()
     
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //跳转方法
    func composeShow(target: UIViewController) {
        
        self.target = target
        target.view.addSubview(self)
        setupButtonsAnim(true)
        
    }
    
    //点击消失
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        setupButtonsAnim(false)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.25 *  Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()

        }

        
    }
    
    
    func setupButtonsAnim(isUp: Bool) {
        
        let margin: CGFloat = isUp ? -350 : 350
//        let set = isUp ? 
        let set = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        for (i,value) in set {
            // 设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置tovalue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            // 开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 弹性系数
            anim.springBounciness = 12
            // 动画速度
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
            
        }
        
    }

    //setupUI
  func  setupUI() {
    
    backgroundColor = UIColor.grayColor()
    self.addSubview(bgImageView)
    self.addSubview(logoImageView)
    addChlidButton()
    bgImageView.snp_makeConstraints { (make) -> Void in
        
        make.edges.equalTo(self).offset(UIEdgeInsetsZero)
    }
    
    logoImageView.snp_makeConstraints { (make) -> Void in
        
        make.top.equalTo(self).offset(100)
        make.centerX.equalTo(self)
    }
    }
    
    func buttonClick(button:WJComposeButton) {
        
        UIView.animateWithDuration(0.2, animations: { () -> Void in
            
            for value in self.buttons {
                
                value.alpha = 0.2
                if value == button {
                    
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else {
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.2, animations: { () -> Void in
                    for value in self.buttons {
                        
                         value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    }, completion: { (_) -> Void in
                        
                        guard let nameVC = button.composeButtonInfos?.nextvc else{
                            return
                        }
                        guard let pc = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else {
                            return
                        }

                        guard let nc = NSClassFromString("\(pc).\(nameVC)") as? UIViewController.Type else {

                            return
                        }
                        
                        let tempVC = nc.init()
                        
                        let nac = UINavigationController(rootViewController: tempVC)
                        self.target?.presentViewController(nac, animated: false, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                        
                })
        }
        
    }
    
    //添加按钮
    func addChlidButton() {
        
        composeButtonInfos = getComposeButtonInfos()
        
        let childBtnW: CGFloat = 80
        let childBtnH: CGFloat = 110
        let childBenMargin:(CGFloat) = (SCREENW - childBtnW*3)/4
        
        for (i,value) in composeButtonInfos.enumerate() {
            
        let col = CGFloat(i % 3)
        let row = CGFloat(i / 3)
            
            let btn = WJComposeButton()
            
            btn.composeButtonInfos = value
            btn.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
//            btn.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Highlighted)
            btn.setTitle(value.title, forState: UIControlState.Normal)
            btn.frame = CGRect(x: childBenMargin + (childBtnW + childBenMargin) * col, y: (childBtnH + childBenMargin) * row + SCREENH, width: childBtnW  , height: childBtnH)
            btn.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            addSubview(btn)
            
           buttons.append(btn)
            
        }
            }
    
    
    
    //plist读取数据
    func getComposeButtonInfos() -> [WJComposeButtonInfo]{
        
        let filePath =  NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let dataArray = NSArray(contentsOfFile: filePath)!
        
        var tempArray: [WJComposeButtonInfo] = [WJComposeButtonInfo]()
        
        for dic in dataArray {
            
            let composeButtonInfos = WJComposeButtonInfo(dict: dic as! [String : AnyObject])
            
            tempArray.append(composeButtonInfos)
        }
        return tempArray
    }
    
    
    
    //懒加载控件
   private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    private lazy var logoImageView: UIImageView = UIImageView(imgName: "compose_slogan")
    
}
